﻿Imports TMySQL
Public Class frmTableDef
    Private _Table As IHasColumns
    Private _Edited As Boolean
    Private _GridMySQLColumn As TGridMySQLColumn

    Private Enum TCol As Integer
        coColumnName = 0
        coColumnType = 1
        coDataLength = 2
        coCharacterSet = 3
        coDefault = 4
        coNullable = 5
        coCollation = 6
        coAttribute = 7
        coAutoIncrement = 8
        coComment = 9
        coCondition = 10
    End Enum

    Private _PageIndex As Integer = 0
    Private _Count As Integer = 0
    Public ReadOnly Property Edited() As Boolean
        Get
            Return _Edited
        End Get
    End Property
    Private ReadOnly Property ColumnTypes() As TMyColumnTypes
        Get
            Return frmMain.ColumnTypes
        End Get
    End Property
    Private ReadOnly Property Attributes() As TMyAttributes
        Get
            Return frmMain.Attributes
        End Get
    End Property
    Private ReadOnly Property Collations() As TMyCollations
        Get
            Return frmMain.Collations
        End Get
    End Property
    Private ReadOnly Property CharacterSets() As TMyCharacterSets
        Get
            Return frmMain.CharacterSets
        End Get
    End Property
    Public Sub RefreshData()
        _Table.Conditions = Me.Conditions
        _Table.Limit = Me.Limit
        _Table.Offset = Me.Offset
        _Table.RefreshData()
        GridData.DataSource = _Table.DataTable
    End Sub

    Private Sub cmdFirst_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdFirst.Click
        Me.PageIndex = 0
    End Sub

    Private Sub cmdShowAll_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdShowAll.CheckedChanged
        lblPageCount.Text = Me.PageCount
        cmdFirst.Visible = Not cmdShowAll.Checked
        cmdPrev.Visible = Not cmdShowAll.Checked
        cmdNext.Visible = Not cmdShowAll.Checked
        cmdLast.Visible = Not cmdShowAll.Checked
        txtLimit.Visible = Not cmdShowAll.Checked
    End Sub

    Private Sub cmdPrev_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdPrev.Click
        If Me.PageIndex > 0 Then
            Me.PageIndex -= 1
            Me.RefreshData()
        End If
    End Sub

    Private Sub cmdNext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdNext.Click
        If Me.Limit = 0 Then
            Return
        End If
        If Me.PageIndex < Me.PageCount Then
            Me.PageIndex += 1
            Me.RefreshData()
        End If
    End Sub

    Private Sub cmdLast_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdLast.Click
        If Me.Limit > 0 Then
            Me.PageIndex = Me.PageCount
            Me.RefreshData()
        End If
    End Sub

    Private Sub txtLimit_Validated(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtLimit.Validated
        lblPageCount.Text = Me.PageCount
    End Sub

    Public ReadOnly Property Limit() As Integer
        Get
            If Not cmdShowAll.Checked Then
                Return Common.StrToIntDef(txtLimit.Text, frmMain.GeneralSettings.DefaultLimit)
            Else
                Return 0
            End If
        End Get
    End Property

    Public Property PageIndex() As Integer
        Get
            Return _PageIndex
        End Get
        Set(ByVal value As Integer)
            _PageIndex = value
            lblPageIndex.Text = value.ToString
        End Set
    End Property

    Public ReadOnly Property Offset() As Integer
        Get
            If Not cmdShowAll.Checked Then
                Return Me.PageIndex * Me.Limit
            Else
                Return 0
            End If
        End Get
    End Property

    Public ReadOnly Property Count() As Integer
        Get
            Return _Count
        End Get
    End Property

    Public ReadOnly Property PageCount() As Integer
        Get
            If Me.Limit > 0 Then
                Return Convert.ToInt32(System.Math.Truncate(_Count / Me.Limit))
            Else
                Return 0
            End If
        End Get
    End Property

    Private Sub InitCount()
        _Count = _Table.GetRowCount
    End Sub

    Public Sub New(ByVal ATable As IHasColumns)
        Me.New()
        _Table = ATable
        _GridMySQLColumn = New TGridMySQLColumn(GridCol, ATable, True)
        _GridMySQLColumn.InitColumns()
        InitFrm()
    End Sub

    Private Sub New()
        ' この呼び出しは、Windows フォーム デザイナで必要です。
        InitializeComponent()
        ' InitializeComponent() 呼び出しの後で初期化を追加します。
    End Sub
    Private ReadOnly Property GeneralSettings() As TGeneralSettings
        Get
            Return frmMain.GeneralSettings
        End Get
    End Property

    Private Sub InitFrm()
        cmdAddColumn.Enabled = _Table.GetType Is GetType(TMyTable)
        cmdDeleteColumn.Enabled = _Table.GetType Is GetType(TMyTable)
        GridCol.Rows.Clear()

        frmMain.GeneralSettings.ApplyAll(Me)
        frmMain.GridSettings.ApplyAll(Me)
        txtTableSchema.Text = _Table.TableSchema
        txtTableName.Text = _Table.TableName
        txtTableComment.Text = _Table.TableComment
        GridCol.AutoGenerateColumns = False
        _Table.RefreshColumn()
        GridCol.SuspendLayout()
        Try
            InitHeader()
            For i As Integer = 0 To _Table.ColumnCount - 1
                Dim item As New DataGridViewRow
                item.CreateCells(GridCol)
                item.Cells(TCol.coColumnName).Value = _Table.Columns(i).ColumnName
                item.Cells(TCol.coColumnType).Value = _Table.Columns(i).DataType.ToUpper
                item.Cells(TCol.coDataLength).Value = _Table.Columns(i).DataLength
                item.Cells(TCol.coCharacterSet).Value = _Table.Columns(i).CharacterSetName
                item.Cells(TCol.coDefault).Value = _Table.Columns(i).ColumnDefault
                item.Cells(TCol.coNullable).Value = _Table.Columns(i).IsNullable.Equals("Yes")
                item.Cells(TCol.coCollation).Value = _Table.Columns(i).CollationName
                item.Cells(TCol.coAttribute).Value = _Table.Columns(i).Attribute.ToUpper
                item.Cells(TCol.coAutoIncrement).Value = _Table.Columns(i).AutoIncrement
                item.Cells(TCol.coComment).Value = _Table.Columns(i).ColumnComment
                item.Cells(TCol.coCondition).Value = String.Empty
                GridCol.Rows.Add(item)
            Next
            InitCount()
            cmdShowAll.Checked = GeneralSettings.ShowAll
            txtLimit.Text = GeneralSettings.DefaultLimit
            lblPageCount.Text = Me.PageCount
            lblPageIndex.Text = _PageIndex.ToString
            If GeneralSettings.ShowData Then
                RefreshData()
            End If
        Finally
            GridCol.ResumeLayout()
            GridCol.Hide()
            GridCol.Show()
            _Edited = False
        End Try
    End Sub

    Private Sub InitHeader()
        If _Table.GetType IsNot GetType(TMyTable) Then
            For i As Integer = 0 To GridCol.Columns.Count - 1
                GridCol.Columns(i).ReadOnly = True
            Next
        End If
        GridCol.Columns(TCol.coCondition).ReadOnly = False
        Common.SetGridAllowSorting(GridCol, DataGridViewColumnSortMode.NotSortable)
    End Sub

    Public ReadOnly Property Conditions() As String
        Get
            Dim sb As New System.Text.StringBuilder
            If txtCondition.Text.Trim.Length > 0 Then
                sb.Append("and ").AppendLine(txtCondition.Text)
            End If

            For i As Integer = 0 To GridCol.RowCount - 1
                If GridCol.Item(TCol.coCondition, i).Value IsNot Nothing Then
                    If GridCol.Item(TCol.coCondition, i).Value.ToString.Length > 0 Then
                        sb.Append("and ").Append(GridCol.Item(TCol.coColumnName, i).Value.ToString).AppendLine(GridCol.Item(TCol.coCondition, i).Value.ToString)
                    End If
                End If
            Next
            Return sb.ToString
        End Get
    End Property

    Public Sub ApplyControlFontSettings(ByVal AControl As Control, ByVal ASettings As TGeneralSettings)
        For Each ctrl As Control In Me.Controls
            If ctrl.Controls.Count > 0 Then
                ApplyControlFontSettings(ctrl, ASettings)
            End If
            If Not ctrl.GetType Is GetType(Sgry.Azuki.WinForms.AzukiControl) Then
                ctrl.Font = ASettings.Font
                ctrl.BackColor = ASettings.BackColor
                ctrl.ForeColor = ASettings.ForeColor
            End If
        Next
    End Sub

    Private Sub txtLimit_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtLimit.KeyPress
        If e.KeyChar < "0"c OrElse e.KeyChar > "9"c Then
            e.Handled = True
        End If
    End Sub

    Private Sub GridCol_DataError(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewDataErrorEventArgs) Handles GridCol.DataError, GridData.DataError
        e.Cancel = True
        Return
    End Sub

    Private Sub GridCol_CellValueChanged(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles GridCol.CellValueChanged
        _Edited = True
    End Sub

    Public Sub AlterTable()
        Dim sb As New System.Text.StringBuilder
        Dim isFirst As Boolean = True
        Dim myQuery As New TMyQuery
        myQuery.Session = frmMain.Connection
        Try
            myQuery.SQL.Append(_GridMySQLColumn.AlterTableChangeSQL)
            myQuery.Execute()
            _Table.RefreshAll()
            InitFrm()
        Catch ex As Exception
            Throw New Exception(ex.Message)
        Finally
            myQuery.Dispose()
        End Try
    End Sub

    Private Sub cmdDeleteColumn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdDeleteColumn.Click
        If _Table.GetType IsNot GetType(TMyTable) Then
            Return
        End If

        If GridCol.SelectedCells.Count <= 0 Then
            Return
        End If
        Dim row As Integer = GridCol.SelectedCells(0).RowIndex
        Dim colName As String = GridCol.Item(TCol.coColumnName, row).Value.ToString
        If MsgBox("列 「" & colName & "」を削除します。よろしいですか？", MsgBoxStyle.Question Or MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
            Cursor.Current = Cursors.WaitCursor
            Try
                DirectCast(_Table, TMyTable).DropColumn(colName)
                Call MsgBox("削除しました", MsgBoxStyle.Information)
                InitFrm()
            Catch ex As Exception
                Call MsgBox("エラーが発生しました。" & vbNewLine & ex.Message, MsgBoxStyle.Exclamation)
            Finally
                Cursor.Current = Cursors.Default
            End Try
        End If
    End Sub

    Private Sub cmdAddColumn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdAddColumn.Click
        If _Table.GetType IsNot GetType(TMyTable) Then
            Return
        End If
        Dim frmRet As New frmAddColumns(DirectCast(_Table, TMyTable))
        Try
            If frmRet.ShowEx() = MsgBoxResult.Ok Then
                InitFrm()
            End If
        Finally
            frmRet.Dispose()
        End Try
    End Sub
End Class